package cn.itcast.mytest;

import cn.itcast.n2.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;

public class Test02 {
    public static void main(String[] args) {
        MessageQueue messageQueue = new MessageQueue(2);

        for (int i = 0; i < 3; i++) {
            int id = i;

            new Thread(() -> {
                messageQueue.put(new Message(id, "值"+id));
            }, "生产者" + i).start();


        }
        new Thread(() -> {
            while (true) {
                Sleeper.sleep(1);
                messageQueue.take();
            }
        }, "消费者").start();

    }
}

@Slf4j(topic = "c.test02")
class MessageQueue{
    private LinkedList<Message> list = new LinkedList<>();
    private int capcity;

    public MessageQueue(int capcity) {
        this.capcity = capcity;
    }

    public Message take(){

        synchronized (list){
            while (list.isEmpty()){
                try {
                    log.debug("消费者等待");
                    list.wait();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            Message message = list.removeFirst();
            log.debug("消费任务" + message);
            list.notifyAll();
            return message;
        }
    }

    public void put(Message message){
        synchronized (list){
            while (list.size() == capcity){
                try {
                    log.debug("生产者等待");
                    list.wait();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.addLast(message);
            log.debug("产生任务" + message);
            list.notifyAll();
        }
    }
}

final class Message{
    private int id;
    private Object value;

    public Message(int id, Object value) {
        this.id = id;
        this.value = value;
    }

    public int getId() {
        return id;
    }

    public Object getValue() {
        return value;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", value=" + value +
                '}';
    }
}